package com.ocean.client.extension.security.handler;

import com.ocean.cache.redis.IRedisCache;
import com.ocean.client.extension.ConstantsCacheExtension;
import com.ocean.client.extension.security.core.UmsMemberDetails;
import com.ocean.core.util.JwtUtil;
import com.ocean.core.util.response.ResultSet;
import com.ocean.security.handler.RestAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权成功
 *
 * @author zhang
 * @since 2021/9/10
 */
@Component
public class RestAuthenticationSuccess extends RestAuthenticationSuccessHandler {

    @Autowired
    private IRedisCache iRedisCache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        httpServletResponse.setStatus(200);
        UmsMemberDetails principal = (UmsMemberDetails) authentication.getPrincipal();
        String token = JwtUtil.generateJwtToken(principal.getMemberId());
        iRedisCache.set(ConstantsCacheExtension.getInstance().getAuthenticationPrefix() + principal.getMemberId(), principal, JwtUtil.EXPIRE_30);
        principal.setPassword(token);
        httpServletResponse.getWriter().print(ResultSet.ok(principal));
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
